package edu.ccut.saturn.workflow.startWorkFlowModule.code;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;
import edu.ccut.saturn.workflow.common.Constants;
import edu.ccut.saturn.workflow.common.WorkFlowTools;
import edu.ccut.saturn.workflow.model.ActivityInfo;

public class GetParticipantFromCreator implements IParticipantGeter {

	@SuppressWarnings("unchecked")
	public List<SaturnData> getParticipant(SaturnData workItemInstance,
			ActivityInfo currentActivityInfo, IParameterContext parameterContext)
			throws Exception {
		SaturnData workFlowInstance = (SaturnData) parameterContext
				.getParameterValue(0);
		Connection conn = parameterContext.getConnection();
		List<SaturnData> wiParticipantDatas = new ArrayList<SaturnData>();
		Map<String, String> workFlowParamMap = (Map<String, String>) parameterContext
				.getParameterValue(2);
		// 如果数据库中没有当前实例的任务，则从workFlowParamMap中取creator

		// String sql = "select count(*) from wf_workitem_instance where
		// process_instance_id='"+workItemInstance.get("process_instance_id")+"'";
		// "select count(*)from wf_process_instance where
		// process_instance_id='"+previousActivityInstance.get("process_instance_id")+"'";
		// int count = Operation.dataBase().queryCountBySQL(sql, conn);
		int count = 0;
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("process_instance_id", workItemInstance.get("process_instance_id")+"");
		ArrayList<SaturnData> result = Operation.dataBase().queryBySaturnSql(
				Constants.SATURNDATA_WF_COUNT,
				"GET_COUNT_WORKITENS_BY_PEOCESSINSTANCEID", paramMap, conn);

		if (result != null) {
			count = Integer.parseInt(result.get(0).get("count") + "");
		}

		String userName = null;
		String userSerialNo = null;
		if (count == 0) {// 是开始节点
			userName = workFlowParamMap.get("creator_name");
			userSerialNo = workFlowParamMap.get("creator");
			// workItemId = workItemInstance.get("workitem_id")+"";

		} else {// 其他节点
			// 如果有 ，则从数据库中取出creator
			userName = workFlowInstance.get("creator_name") + "";
			userSerialNo = workFlowInstance.get("creator") + "";
			// workItemId = workItemInstance.get("workitem_id")+"";
		}
		SaturnData wiParticipantData = WorkFlowTools
				.getParticipantInstanceWithValues(userSerialNo, userName);
		wiParticipantDatas.add(wiParticipantData);
		return wiParticipantDatas;
	}

}
